import { Coupon } from './coupon-model.js';
var coupon = new Coupon();
Page({
  data: {
    type:1,
    items: [
      { val: '1', value: '充值券',checked: 'true'},
      { val: '2', value: '礼物券'}
    ],
    btnText: '激活',
    btnType:'disable',
    args:{
      conditions:{
        code: '',
        password: '',
      },
      coupon_id:''
    },
    sending : false //是否正在激活
  },

  onLoad: function (options) {
    
  },

  //提交表单
  formSubmit:function(e){
    if (!this.data.args.conditions.code || !this.data.args.conditions.password) {
      wx.showToast({
        title: '请先填写卡号和密钥',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.sub();
  },

  //激活会员卡
  sub: function () {
    var that = this;
   
    if (this.data.sending){
      return false;
    }
    this.data.sending = true;
    this.setData({btnText:'正在激活...'});

    if (this.data.type == 1){
      //充值券
      var params = {
        card_no:this.data.args.conditions.code,
        password: this.data.args.conditions.password
      };
      coupon.recharge(params, (data) => {
        that.data.sending = false;
        this.setData({ btnText: '激活' });
        if (data.status == 0) {
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000
          })
          return false;
        } else if (data.status == 1) {
          wx.showToast({
            title: '恭喜您,已充值到您的余额',
            icon: 'success',
            duration: 2000
          })
          wx.redirectTo({
            url: '/pages/center/wallet',
          })
        }
      });
    } else if (this.data.type == 2){
      //礼物券
      var params = that.data.args;
      coupon.receive(params, (data) => {
        that.data.sending = false;
        this.setData({ btnText: '激活' });
        if (data.status == 0) {
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000
          })
          return false;
        } else if (data.status == 1) {
          wx.showToast({
            title: '恭喜您激活成功',
            icon: 'success',
            duration: 2000
          })
          wx.redirectTo({
            url: 'my',
          })
        }
      });
    }
   
  },
  //获取用户输入的卡号内容
  carChange:function(e){
    var val = e.detail.value;
    this.setData({
      'args.conditions.code':val
    });
    this.btnChange();
  },
  //获取用户输入的密钥内容
  passChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.conditions.password': val
    });
    this.btnChange();

  },
  //获取用户选择的会员卡类型
  radioChange:function(e){
    var val = e.detail.value;
    this.setData({
      type: val
    });
  },
  //判断激活按钮的样式
  btnChange: function () {
    let type = 'disable'
    if (this.data.args.conditions.code && this.data.args.conditions.password){
      type = '';
    }
    this.setData({
      btnType: type
    });
  }
})